package com.itbaizhan.service.impl;

import com.itbaizhan.dao.ItemDao;
import com.itbaizhan.dao.OrderDao;
import com.itbaizhan.dao.RedisDao;
import com.itbaizhan.pojo.Item;
import com.itbaizhan.pojo.Order;
import com.itbaizhan.service.BuyactionConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author spf
 * @date 2024/3/8
 * @time 9:40
 */

@Service
public class BuyactionConsumerServiceImpl implements BuyactionConsumerService {

    @Autowired
    private RedisDao redisDao;
    @Autowired
    private ItemDao itemDao;
    @Autowired
    private OrderDao orderDao;
    @Value("${livegoods.cache.names.item.prefix}")
    private String itemPrefix;
    @Value("${livegoods.cache.names.item.suffix}")
    private String itemSuffix;

    @Override
    public boolean buyaction(String itemId, String user) {
        String key = itemPrefix + "::" + itemSuffix + "(" + itemId + ")";
        Item item = redisDao.get(key);
        item.setIsRented(true);
        boolean result = redisDao.set(key, item);
        if (result){
            long rows = itemDao.update(itemId, true);
            if (rows == 1){
                Order order = new Order();
                order.setItemId(itemId);
                order.setUsername(user);
                order.setPrice(String.valueOf(item.getPrice()));
                order.setTitle(item.getTitle());
                order.setCommentState(0);
                order.setHouseType(item.getHouseType());
                order.setImg(item.getImgs());

                orderDao.save(order);

                return true;
            }
        }
        return false;
    }
}
